package com.wxp.demo06.shared;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.wxp.demo06.R;
import com.wxp.demo06.util.ViewUtil;

import java.util.Random;

/**
 * 1.2.1 Share用户登录-记住密码
 */
public class ShareLoginMainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {

    private TextView tv_password;
    private EditText et_password;
    private Button btn_forget;
    private CheckBox ck_remember;
    private EditText et_phone;
    private RadioButton rb_password;
    private RadioButton rb_verifycode;
    private Button btn_login;
    private ActivityResultLauncher<Intent> activityResult;
    private SharedPreferences preferences;
    /**
     * 系统密码
     */
    private static String mPassword = "123456";
    private String mVerifycode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_share_login_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        this.setTitle("5.1 Share用户登录");

        RadioGroup rg_login = this.findViewById(R.id.rg_login);
        tv_password = this.findViewById(R.id.tv_password);
        et_password = this.findViewById(R.id.et_password);
        btn_forget = this.findViewById(R.id.btn_forget);
        ck_remember = this.findViewById(R.id.ck_remember);
        et_phone = this.findViewById(R.id.et_phone);
        rb_password = this.findViewById(R.id.rb_password);
        rb_verifycode = this.findViewById(R.id.rb_verifycode);
        btn_login = this.findViewById(R.id.btn_login);

        //设置事件
        //给rg_login设置单选监听器
        rg_login.setOnCheckedChangeListener(this);
        //给et_phone添加文本变更监听器
        et_phone.addTextChangedListener(new HideTextWatcher(et_phone, this.getResources().getInteger(R.integer.phone_max_length)));
        //给et_password添加文本变更监听器
        et_password.addTextChangedListener(new HideTextWatcher(et_password, this.getResources().getInteger(R.integer.password_max_length)));
        //给btn_forget设置点击事件
        btn_forget.setOnClickListener(this);
        btn_login.setOnClickListener(this);

        //注册回调事件
        activityResult = this.registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            Intent intent = result.getData();
            if (intent != null && result.getResultCode() == Activity.RESULT_OK) {
                // 用户密码已改为新密码，故更新密码变量
                mPassword = intent.getStringExtra("new_password");
            }
        });

        //定义共享变量
        preferences = getSharedPreferences("config", Context.MODE_PRIVATE);
        reload();
    }


    /**
     * 重新加载数据
     */
    private void reload() {
        boolean isRemember = preferences.getBoolean("isRemember", false);
        if (isRemember) {
            String phone = preferences.getString("phone", "");
            et_phone.setText(phone);

            String password = preferences.getString("password", "");
            et_password.setText(password);
            ck_remember.setChecked(true);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == R.id.rb_password) {
            //密码登录
            tv_password.setText(this.getString(R.string.login_password));
            et_password.setHint(this.getString(R.string.input_password));
            btn_forget.setText(this.getString(R.string.forget_password));
            ck_remember.setVisibility(View.VISIBLE);
        } else if (checkedId == R.id.rb_verifycode) {
            //验证码登录
            tv_password.setText(this.getString(R.string.verifycode));
            et_password.setHint(this.getString(R.string.input_verifycode));
            btn_forget.setText(this.getString(R.string.get_verifycode));
            ck_remember.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        String phone = et_phone.getText().toString().trim();
        if (phone.length() != this.getResources().getInteger(R.integer.phone_max_length)) {
            //提示信息
            Toast.makeText(this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
            return;
        }

        if (v.getId() == R.id.btn_forget) {
            if (rb_password.isChecked()) {
                //密码方式登录
                //跳转找回密码页面，并传递手机号码
                Intent intent = new Intent(this, ShareLoginForgetActivity.class);
                //添加手机号码
                intent.putExtra("phone", phone);
                //启动页面并获取结果
                activityResult.launch(intent);
            } else if (rb_verifycode.isChecked()) {
                //验证码方式登录
                //生成6位验证码
                mVerifycode = String.format("%06d", new Random().nextInt(999999));
                //弹出对话框，提示用户记住验证码
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                //设置图标
                builder.setIcon(android.R.drawable.ic_popup_reminder);
                // 设置对话框的标题文本
                builder.setTitle("请记住验证码");
                builder.setMessage("手机号" + phone + "，本次验证码是：" + mVerifycode + "，请输入验证码");
                builder.setPositiveButton("好的", null);
                builder.create().show();
            }

        } else if (v.getId() == R.id.btn_login) {
            //登录事件
            if (rb_password.isChecked()) {
                //校验密码
                if (!mPassword.equals(et_password.getText().toString())) {
                    Toast.makeText(this, "请输入正确的密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                //提示用户登录成功
                loginSuccess();

            } else if (rb_verifycode.isChecked()) {
                //校验验证码
                if (!mVerifycode.equals(et_password.getText().toString())) {
                    Toast.makeText(this, "请输入正确的验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                //提示用户登录成功
                loginSuccess();
            }

        }
    }

    /**
     * 登录成功
     */
    private void loginSuccess() {
        String desc = String.format("您的手机号码是%s，恭喜你通过登录验证，点击“确定”按钮返回上个页面",
                et_phone.getText().toString());
        // 以下弹出提醒对话框，提示用户登录成功
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this);
        builder.setTitle("登录成功");
        builder.setMessage(desc);
        builder.setPositiveButton("确定返回", (dialog, which) -> {
            // 结束当前的活动页面
            finish();
        });
        builder.setNegativeButton("我再看看", null);
        androidx.appcompat.app.AlertDialog dialog = builder.create();
        dialog.show();

        //保存密码信息
        if (ck_remember.isChecked()) {
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("phone", et_phone.getText().toString());
            editor.putString("password", et_password.getText().toString());
            editor.putBoolean("isRemember", ck_remember.isChecked());
            editor.apply();
        }
    }

    /**
     * 隐藏文本监听类
     */
    private class HideTextWatcher implements TextWatcher {
        private EditText editText;
        private int maxLength;

        public HideTextWatcher(EditText editText, int maxLength) {
            this.editText = editText;
            this.maxLength = maxLength;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.toString().length() == maxLength) {
                //隐藏输入法键盘
                ViewUtil.hideOneInputMethod(ShareLoginMainActivity.this, editText);
            }
        }
    }
}